package com.example.tms.controller;

//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONArray;
//import com.alibaba.fastjson.JSONObject;
//import com.example.tms.bean.CycleInfo;
import com.example.tms.bean.ReturnInfo;
import com.example.tms.bean.RoadInfo;
import com.example.tms.bean.RoadView;
import com.example.tms.mapper.*;
import com.example.tms.tools.GlobalParam;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.*;
import java.util.*;
import com.example.tms.annotation.*;

/**
 * 线路信息
 */
@RestController
public class RoadController {

    private final RoadMapper roadMapper;
    private final RoadVMapper roadVMapper;
    private final CstmrMapper cstmrMapper;
    private final AreaMapper areaMapper;
    private final WaybillMapper waybillMapper;
//    private final CycleMapper cycleMapper;

    @Autowired
    public RoadController(RoadMapper roadMapper, RoadVMapper roadVMapper, CstmrMapper cstmrMapper, AreaMapper areaMapper, WaybillMapper waybillMapper){
        this.roadMapper = roadMapper;
        this.roadVMapper = roadVMapper;
        this.cstmrMapper = cstmrMapper;
        this.areaMapper = areaMapper;
//        this.cycleMapper = cycleMapper;
        this.waybillMapper = waybillMapper;
    }

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //查询线路信息列表
    @RequiresPermissions("151")
    @RequestMapping(value = "road",method = RequestMethod.GET)
    public ReturnInfo getRoadinfoAll(@RequestParam(required = false, defaultValue = "") String xlmczj,
                                     @RequestParam(required = false, defaultValue = "") String khjczj,
                                     @RequestParam(required = false, defaultValue = "") String qymczj,
                                     @RequestParam(required = false, defaultValue = "") String leixing,
                                     @RequestParam(required = false, defaultValue = "") String xq){
        List<RoadView> result = roadVMapper.findAll((Root<RoadView> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder)->{
            Path<Boolean> p1 = root.get("sfcz");
            Predicate predicate = criteriaBuilder.equal(p1,true);
            if(!xlmczj.equals("")&&!xlmczj.equals("null")){
                Path<String> p2 = root.get("xlmc");
                Path<String> p3 = root.get("xlzjm");
                Predicate predicate1 = criteriaBuilder.or(criteriaBuilder.like(p2,"%"+xlmczj+"%"),criteriaBuilder.like(p3,"%"+xlmczj+"%"));
                predicate = criteriaBuilder.and(predicate,predicate1);
            }
            if(!khjczj.equals("")&&!khjczj.equals("null")){
                Path<String> p4 = root.get("khjc");
                Path<String> p5 = root.get("khzjm");
                Predicate predicate2 = criteriaBuilder.or(criteriaBuilder.like(p4,"%"+khjczj+"%"),criteriaBuilder.like(p5,"%"+khjczj+"%"));
                predicate = criteriaBuilder.and(predicate,predicate2);
            }
            if(!qymczj.equals("")&&!qymczj.equals("null")){
                Path<String> p6 = root.get("qymc");
                Path<String> p7 = root.get("zjm");
                Predicate predicate3 = criteriaBuilder.or(criteriaBuilder.like(p6,"%"+qymczj+"%"),criteriaBuilder.like(p7,"%"+qymczj+"%"));
                predicate = criteriaBuilder.and(predicate,predicate3);
            }
            if(!leixing.equals("")&&!leixing.equals("null")){
                predicate = criteriaBuilder.and(predicate,criteriaBuilder.equal(root.get("leixing").as(String.class),leixing));
            }
            if(!xq.equals("")&&!xq.equals("null")){
                switch (xq){
                    case "星期一":
                        predicate = criteriaBuilder.and(predicate,criteriaBuilder.equal(root.get("yxzqzhouyi").as(Boolean.class),true));
                        break;
                    case "星期二":
                        predicate = criteriaBuilder.and(predicate,criteriaBuilder.equal(root.get("yxzqzhouer").as(Boolean.class),true));
                        break;
                    case "星期三":
                        predicate = criteriaBuilder.and(predicate,criteriaBuilder.equal(root.get("yxzqzhousan").as(Boolean.class),true));
                        break;
                    case "星期四":
                        predicate = criteriaBuilder.and(predicate,criteriaBuilder.equal(root.get("yxzqzhousi").as(Boolean.class),true));
                        break;
                    case "星期五":
                        predicate = criteriaBuilder.and(predicate,criteriaBuilder.equal(root.get("yxzqzhouwu").as(Boolean.class),true));
                        break;
                    case "星期六":
                        predicate = criteriaBuilder.and(predicate,criteriaBuilder.equal(root.get("yxzqzhouliu").as(Boolean.class),true));
                        break;
                    case "星期日":
                        predicate = criteriaBuilder.and(predicate,criteriaBuilder.equal(root.get("yxzqzhouri").as(Boolean.class),true));
                        break;
                    default:
                        break;
                }
            }
            criteriaQuery.where(predicate);
            criteriaQuery.orderBy(criteriaBuilder.desc(root.get("lasttime")));
            return criteriaQuery.getRestriction();
        });
        return ReturnInfo.info2(result);
//        JSONArray ja = JSONArray.parseArray(JSON.toJSONString(result));
//        for (Object aJa : ja) {
//            JSONObject job = (JSONObject) aJa;
//            CycleInfo cycleInfo1 = cycleMapper.findTop1ByXlidAndYxzqAndYxrqLessThanEqualOrderByTjsjDesc(job.getString("xlid"),"周日",GlobalParam.getSRq());
//            if(cycleInfo1==null){
//                job.put("yxzqzhouri",false);
//            }else {
//                job.put("yxzqzhouri",cycleInfo1.getSfyx());
//            }
//            CycleInfo cycleInfo2 = cycleMapper.findTop1ByXlidAndYxzqAndYxrqLessThanEqualOrderByTjsjDesc(job.getString("xlid"),"周一",GlobalParam.getSRq());
//            if(cycleInfo2==null){
//                job.put("yxzqzhouyi",false);
//            }else {
//                job.put("yxzqzhouyi",cycleInfo2.getSfyx());
//            }
//            CycleInfo cycleInfo3 = cycleMapper.findTop1ByXlidAndYxzqAndYxrqLessThanEqualOrderByTjsjDesc(job.getString("xlid"),"周二",GlobalParam.getSRq());
//            if(cycleInfo3==null){
//                job.put("yxzqzhouer",false);
//            }else {
//                job.put("yxzqzhouer",cycleInfo3.getSfyx());
//            }
//            CycleInfo cycleInfo4 = cycleMapper.findTop1ByXlidAndYxzqAndYxrqLessThanEqualOrderByTjsjDesc(job.getString("xlid"),"周三",GlobalParam.getSRq());
//            if(cycleInfo4==null){
//                job.put("yxzqzhousan",false);
//            }else {
//                job.put("yxzqzhousan",cycleInfo4.getSfyx());
//            }
//            CycleInfo cycleInfo5 = cycleMapper.findTop1ByXlidAndYxzqAndYxrqLessThanEqualOrderByTjsjDesc(job.getString("xlid"),"周四",GlobalParam.getSRq());
//            if(cycleInfo5==null){
//                job.put("yxzqzhousi",false);
//            }else {
//                job.put("yxzqzhousi",cycleInfo5.getSfyx());
//            }
//            CycleInfo cycleInfo6 = cycleMapper.findTop1ByXlidAndYxzqAndYxrqLessThanEqualOrderByTjsjDesc(job.getString("xlid"),"周五",GlobalParam.getSRq());
//            if(cycleInfo6==null){
//                job.put("yxzqzhouwu",false);
//            }else {
//                job.put("yxzqzhouwu",cycleInfo6.getSfyx());
//            }
//            CycleInfo cycleInfo7 = cycleMapper.findTop1ByXlidAndYxzqAndYxrqLessThanEqualOrderByTjsjDesc(job.getString("xlid"),"周六",GlobalParam.getSRq());
//            if(cycleInfo7==null){
//                job.put("yxzqzhouliu",false);
//            }else {
//                job.put("yxzqzhouliu",cycleInfo7.getSfyx());
//            }
//        }
//        String jsonStrng = JSON.toJSONString(ja);
//        List<RoadInfo> roadInfos = JSON.parseArray(jsonStrng,RoadInfo.class);
//        return ReturnInfo.info2(roadInfos);
    }

    //查询线路信息列表（基础）
    @RequestMapping(value = "roadlist",method = RequestMethod.GET)
    public ReturnInfo getRoadinfoListAll(){
        List<RoadView> roadInfos = roadVMapper.findBySfczOrderByLasttimeAsc(true);
        List<RoadView> roadList = new ArrayList<>();
        for(RoadView roadView : roadInfos){
            roadList.add(new RoadView(roadView.getXlid(),roadView.getXlmc(),roadView.getXlzjm(),roadView.getKhid(),roadView.getKhjc(),roadView.getKhzjm(),roadView.getQyid(),roadView.getQymc(),roadView.getZjm()));
        }
        return ReturnInfo.info2(roadList);
    }
    @RequestMapping(value = "roadlist/{qyid}",method = RequestMethod.GET)
    public ReturnInfo getRoadInfoKhlist(@PathVariable String qyid){
        return ReturnInfo.info2(roadVMapper.findByQyidAndSfczOrderByLasttimeAsc(qyid, true));
    }
    //查询线路信息
    @RequiresPermissions("151")
    @RequestMapping(value = "road/{xlid}",method = RequestMethod.GET)
    public RoadView getRoadinfo(@PathVariable String xlid){
        return roadVMapper.findByXlidAndSfcz(xlid, true);
    }

    //新建线路信息
    @MonitorRequest
    @RequiresPermissions("152")
    @RequestMapping(value = "road",method = RequestMethod.POST)
    public List<Map<String,Object>> saveRoadinfo(@RequestBody RoadInfo roadInfo){
        List<Map<String,Object>>  list = new ArrayList<>();
        Map<String,Object>  map = new HashMap<>();
        if(roadInfo.getXlmc().equals("") ||!checkXlmc(roadInfo.getXlmc())){
            map.put("xlmc", "0");
        }else if(roadMapper.findByXlmcAndSfcz(roadInfo.getXlmc(),true)!=null) {
            map.put("xlmc", "2");
        }
        if(!roadInfo.getXlzjm().equals("")&&roadMapper.findByXlzjmAndSfcz(roadInfo.getXlzjm(),true)!=null){
            map.put("xlzjm", "2");
        }
        if(!roadInfo.getXlbm().equals("")&&roadMapper.findByXlbmAndSfcz(roadInfo.getXlbm(),true)!=null){
            map.put("xlbm", "2");
        }
        if(roadInfo.getKhid().equals("")){
            map.put("khid", "0");
        }else if(cstmrMapper.findByKhid(roadInfo.getKhid())==null){
            map.put("khid","1");
        }
        if(roadInfo.getQyid().equals("")){
            map.put("qyid", "0");
        }else if(areaMapper.findByQyidAndSfcz(roadInfo.getQyid(),true)==null){
            map.put("qyid", "1");
        }
        if(roadInfo.getXllx().equals("")||!checkXllx(roadInfo.getXllx())){
            map.put("xllx", "0");
        }
        if(!roadInfo.getLeixing().equals("")&&!checkLeixing(roadInfo.getLeixing())){
            map.put("leixing", "0");
        }
        if(!roadInfo.getXlbm().equals("")&&!checkXlinfo(roadInfo.getXlbm())){
            map.put("xlbm", "0");
        }
        if(!roadInfo.getXlzjm().equals("")&&!checkXlinfo(roadInfo.getXlzjm())){
            map.put("xlzjm", "0");
        }
        if(!roadInfo.getHwsl().equals("")&&!checkInteger(roadInfo.getHwsl())){
            map.put("hwsl","0");
        }
        if(!roadInfo.getYunfei().equals("")&&!checknumber(roadInfo.getYunfei())){
            map.put("yunfei","0");
        }
        if(!roadInfo.getGls().equals("")&&!checknumber(roadInfo.getGls())){
            map.put("gls","0");
        }
        if(!roadInfo.getYdj().equals("")&&!checknumber(roadInfo.getYdj())){
            map.put("ydj","0");
        }
        if(!roadInfo.getBuzhu().equals("")&&!checknumber(roadInfo.getBuzhu())){
            map.put("buzhu","0");
        }
        if(!roadInfo.getYlzl().equals("")&&!checkYlzl(roadInfo.getYlzl())){
            map.put("ylzl","0");
        }
        list.add(map);
         if(map.isEmpty()){
             roadInfo.setXlid(UUID.randomUUID().toString().replaceAll("-",""));
             roadInfo.setLasttime(GlobalParam.getTime());
             roadInfo.setSfcz(true);
             roadMapper.save(roadInfo);
             logger.info("新建线路"+roadInfo.toString());
//             CycleInfo cycleInfo1 = new CycleInfo(roadInfo.getXlid(),"周日",roadInfo.getYxzqzhouri());
//             cycleMapper.save(cycleInfo1);
//             CycleInfo cycleInfo2 = new CycleInfo(roadInfo.getXlid(),"周一",roadInfo.getYxzqzhouyi());
//             cycleMapper.save(cycleInfo2);
//             CycleInfo cycleInfo3 = new CycleInfo(roadInfo.getXlid(),"周二",roadInfo.getYxzqzhouer());
//             cycleMapper.save(cycleInfo3);
//             CycleInfo cycleInfo4 = new CycleInfo(roadInfo.getXlid(),"周三",roadInfo.getYxzqzhousan());
//             cycleMapper.save(cycleInfo4);
//             CycleInfo cycleInfo5 = new CycleInfo(roadInfo.getXlid(),"周四",roadInfo.getYxzqzhousi());
//             cycleMapper.save(cycleInfo5);
//             CycleInfo cycleInfo6 = new CycleInfo(roadInfo.getXlid(),"周五",roadInfo.getYxzqzhouwu());
//             cycleMapper.save(cycleInfo6);
//             CycleInfo cycleInfo7 = new CycleInfo(roadInfo.getXlid(),"周六",roadInfo.getYxzqzhouliu());
//             cycleMapper.save(cycleInfo7);
         }
        return list;
    }

    //更新线路信息
    @MonitorRequest
    @RequiresPermissions("153")
    @RequestMapping(value = "road",method = RequestMethod.PUT)
    public List<Map<String,Object>> updateRoadinfo(@RequestBody RoadInfo roadInfo){
        List<Map<String,Object>>  list = new ArrayList<>();
        Map<String,Object>  map = new HashMap<>();
        if(roadInfo.getXlid()==null||roadInfo.getXlid().equals("")){
            map.put("xlid", "0");
        }else if(roadMapper.findByXlid(roadInfo.getXlid())==null){
            map.put("xlid", "1");
        }
        RoadInfo oldRoad = roadMapper.findByXlid(roadInfo.getXlid());
        if(roadInfo.getXlmc().equals("")){
            map.put("xlmc", "0");
        }else if(!roadInfo.getXlmc().equals(oldRoad.getXlmc())&&roadMapper.findByXlmcAndSfcz(roadInfo.getXlmc(),true)!=null) {
            map.put("xlmc", "2");
        }
        if(!roadInfo.getXlzjm().equals(oldRoad.getXlzjm())&&!roadInfo.getXlzjm().equals("")&&roadMapper.findByXlzjmAndSfcz(roadInfo.getXlzjm(),true)!=null){
            map.put("xlzjm", "2");
        }
        if(!roadInfo.getXlbm().equals(oldRoad.getXlbm())&&!roadInfo.getXlbm().equals("")&&roadMapper.findByXlbmAndSfcz(roadInfo.getXlbm(),true)!=null){
            map.put("xlbm", "2");
        }
        if(roadInfo.getKhid().equals("")){
            map.put("khid", "0");
        }else if(cstmrMapper.findByKhid(roadInfo.getKhid())==null){
            map.put("khid","1");
        }
        if(roadInfo.getQyid().equals("")){
            map.put("qyid", "0");
        }else if(areaMapper.findByQyidAndSfcz(roadInfo.getQyid(),true)==null){
            map.put("qyid", "1");
        }
        if(roadInfo.getXllx().equals("")||!checkXllx(roadInfo.getXllx())){
            map.put("xllx", "0");
        }
        if(roadInfo.getXlyxqq().equals("")){
            map.put("xlyxqq", "0");
        }
        if(roadInfo.getXlyxqz().equals("")){
            map.put("xlyxqz", "0");
        }
        if(!roadInfo.getXlyxqq().equals("")&&!roadInfo.getXlyxqz().equals("")&&roadInfo.getXlyxqz().compareTo(roadInfo.getXlyxqq())<0){
            map.put("xlyxqq", "1");
            map.put("xlyxqz", "1");
        }
        if(!roadInfo.getXlbm().equals("")&&!checkXlinfo(roadInfo.getXlbm())){
            map.put("xlbm", "0");
        }
        if(!roadInfo.getXlzjm().equals("")&&!checkXlinfo(roadInfo.getXlzjm())){
            map.put("xlzjm", "0");
        }
        if(!roadInfo.getLeixing().equals("")&&!checkLeixing(roadInfo.getLeixing())){
            map.put("leixing", "0");
        }
        if(!roadInfo.getHwsl().equals("")&&!checkInteger(roadInfo.getHwsl())){
            map.put("hwsl","0");
        }
        if(!roadInfo.getYunfei().equals("")&&!checknumber(roadInfo.getYunfei())){
            map.put("yunfei","0");
        }
        if(!roadInfo.getGls().equals("")&&!checknumber(roadInfo.getGls())){
            map.put("gls","0");
        }
        if(!roadInfo.getYdj().equals("")&&!checknumber(roadInfo.getYdj())){
            map.put("ydj","0");
        }
        if(!roadInfo.getBuzhu().equals("")&&!checknumber(roadInfo.getBuzhu())){
            map.put("buzhu","0");
        }
        list.add(map);
        if(map.isEmpty()){
            roadInfo.setLasttime(GlobalParam.getTime());
            roadInfo.setSfcz(true);
            roadMapper.saveAndFlush(roadInfo);
            logger.info("更新线路"+roadInfo.toString());
//            CycleInfo cycleInfo1 = new CycleInfo(roadInfo.getXlid(),"周日",roadInfo.getYxzqzhouri());
//            cycleMapper.save(cycleInfo1);
//            CycleInfo cycleInfo2 = new CycleInfo(roadInfo.getXlid(),"周一",roadInfo.getYxzqzhouyi());
//            cycleMapper.save(cycleInfo2);
//            CycleInfo cycleInfo3 = new CycleInfo(roadInfo.getXlid(),"周二",roadInfo.getYxzqzhouer());
//            cycleMapper.save(cycleInfo3);
//            CycleInfo cycleInfo4 = new CycleInfo(roadInfo.getXlid(),"周三",roadInfo.getYxzqzhousan());
//            cycleMapper.save(cycleInfo4);
//            CycleInfo cycleInfo5 = new CycleInfo(roadInfo.getXlid(),"周四",roadInfo.getYxzqzhousi());
//            cycleMapper.save(cycleInfo5);
//            CycleInfo cycleInfo6 = new CycleInfo(roadInfo.getXlid(),"周五",roadInfo.getYxzqzhouwu());
//            cycleMapper.save(cycleInfo6);
//            CycleInfo cycleInfo7 = new CycleInfo(roadInfo.getXlid(),"周六",roadInfo.getYxzqzhouliu());
//            cycleMapper.save(cycleInfo7);
        }
        return list;
    }

    //删除线路信息（假删除 线路id）
    @MonitorRequest
    @RequiresPermissions("154")
    @RequestMapping(value = "road/{xlid}",method = RequestMethod.DELETE)
    public ReturnInfo deleteRoadinfo(@PathVariable String xlid){
        String b;
        RoadInfo roadInfo = roadMapper.findByXlid(xlid);
        String xlmc = roadInfo.getXlmc();
        if(roadMapper.findByXlid(xlid)==null){
            b = "删除失败！";
        }/*else if (!waybillMapper.findByXlidandYdzt1(xlmc).isEmpty()) {
            b = "该线路下有运单正在执行，不可删除！";
        }else if (!waybillMapper.findByXlidandYdzt2(xlmc).isEmpty()) {
            b = "该线路下有运单正在执行，不可删除！";
        }else if (!waybillMapper.findByXlidandYdzt3(xlmc).isEmpty()) {
            b = "该线路下有运单正在执行，不可删除！";
        }else if (!waybillMapper.findByXlidandYdzt4(xlmc).isEmpty()) {
            b = "该线路下有运单正在执行，不可删除！";
        }else if (!waybillMapper.findByXlidandYdzt5(xlmc).isEmpty()) {
            b = "该线路下有运单正在执行，不可删除！";
        }*/else{
            roadMapper.DeleteByXlid(xlid);
            b = "删除成功！";
            logger.info("删除线路"+xlid);
        }
        return ReturnInfo.info1(b);
    }

    //检查线路类型格式
    private Boolean checkXllx(String xllx){
        Boolean b = false;
        if(xllx.equals("单开")||xllx.equals("对开")||xllx.equals("当天往返")||xllx.equals("来回")){
            b = true;
        }
        return b;
    }

    //检查类型格式
    private Boolean checkLeixing(String leixing){
        Boolean b = false;
        if(leixing.equals("正班")||leixing.equals("加班")){
            b = true;
        }
        return b;
    }

//    //检查默认车牌号格式
//    private Boolean checkMrcph(String mrcph){
//        Boolean b = false;
//        if(mrcph.matches("^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z][A-Z][A-Z0-9]{4}[A-Z0-9挂学警港澳]$")){
//            b = true;
//        }
//        return b;
//    }

    //检查整数
    private Boolean checkInteger(String integer){
        Boolean b = false;
        if(integer.matches("^[1-9][0-9]{0,14}$")){
            b = true;
        }
        return b;
    }

    //检查数
    private Boolean checknumber(String number){
        Boolean b = false;
        if(number.matches("^[0-9.]{0,14}$")){
            b = true;
        }
        return b;
    }
    //检查线路信息
    private Boolean checkXlinfo(String xlinfo){
        Boolean b = false;
        if(xlinfo.matches("^.{1,20}$")){
            b = true;
        }
        return b;
    }
    //检查线路名称
    private Boolean checkXlmc(String xlmc){
        Boolean b = false;
        if(xlmc.matches("^.{1,30}$")){
            b = true;
        }
        return b;
    }
    //检查运力载量
    private Boolean checkYlzl(String ylzl){
        Boolean b = false;
        if(ylzl.equals("30")||ylzl.equals("20")||ylzl.equals("14")||ylzl.equals("7")||ylzl.equals("4")||ylzl.equals("2")){
            b = true;
        }
        return b;
    }
}
